import axios from "axios";
import {useUserStore} from "@/store/userStore.js";
import {ElMessage} from "element-plus";
import resetMsg from "@/utils/errorMessage.js";
import axiosRetry from "axios-retry";


// 允许携带cookie请求
axios.defaults.withCredentials = true
const httpInstance = axios.create({
    baseURL: 'http://localhost:8002/api/',
    timeout: 20 * 1000,
})
/**
 * 请求重试
 */

axiosRetry(httpInstance, {
    retries: 3, //重试次数
})

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
    config.headers.set("token", localStorage.getItem('token'))
    return config
}, e => Promise.reject(e))


// axios响应式拦截器
// 添加响应拦截器
httpInstance.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    let code = response.data.code;
    // token 失效
    if (code === 401 || code === 10004) {
        useUserStore().userInfo = {}
        localStorage.removeItem('token')
    }
    if (code > 299) {
        console.log(response.data)
        ElMessage.error(response.data.message)
        return Promise.reject(response.data)
    }
    return response.data;

}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。

    if (error.code === "ECONNABORTED") {
        resetMsg("请求超时")
    } else if (error.code === "ERR_NETWORK") {
        resetMsg("网络连接失败")
    } else {
        resetMsg(error.message)
    }
    return Promise.reject(error);
});

export default httpInstance

